import React, { useMemo } from "react";
import "../../css/Studentlist.scss";
import { Form, Input, Button, Table, Tag, Space, Select, message } from "antd";
import request from "../../utils/request";
import { useCallback, useState, useEffect } from "react";
import Froms from "./Forms";
const { Option } = Select;

function Student() {
  const [list, setlist] = useState([]);
  const [page, setpage] = useState(1);
  const [total, settotal] = useState();
  const [visible, setVisible] = useState(false);
  const [type, settype] = useState();
  const [info, setinfo] = useState();
  // 时间
  const add_time = useMemo(() => {
    const data2 = new Date();
    return data2.toLocaleDateString();
  }, []);
  // 删除用户
  const deletelist = useCallback((id) => {
    return () => {
      request.delete("/users/" + id).then(({ data }) => {
        if (data.code === 1) {
          message.success("删除成功");
        } else {
          message.error("删除失败");
          return;
        }
        settotal(total - 1);
      });
    };
  }, []);
  //获取列表数据
  useEffect(() => {
    request
      .get("/users", {
        params: {
          page,
        },
      })
      .then(({ data: { data } }) => {
        setlist(data.list);
        settotal(data.total);
      });
  }, [page, total]);

  // 查询
  const onFinish = useCallback((val) => {
    console.log("nbaval", val);
    request
      .get("users", {
        params: val,
      })
      .then(({ data: { data } }) => {
        console.log("sear", data);
        setlist(data.list);
      });
  }, []);
  // 添加

  const onCreate = useCallback((values) => {
    console.log("Received values of form: ", {
      ...values,
    });
    request
      .post("/users/insert", {
        ...values,
        add_time,
      })
      .then(({ data }) => {
        if (data.code === 1) {
          message.success("添加成功");
          settotal(data.data.total);
        } else {
          message.error("添加错误");
        }
      });
    setVisible(false);
  }, []);
  // 修改
  // 获取信息
  const getinfo = useCallback((info) => {
    return () => {
      setVisible(true);
      settype("change");
      setinfo(info);
    };
  }, []);
  const onChangeinfo = useCallback((val) => {
    const { _id } = val;
    request.put("/users/" + _id, val).then(({ data }) => {
      console.log(data);
      if (data.code === 1) {
        settotal(total + 1);
        message.success("修改成功");
      } else {
        message.error("修改失败");
      }
    });
    setVisible(false);
  }, []);
  // 取消
  const onCancel = useCallback(() => {
    setVisible(false);
  }, []);
  const columns = [
    {
      title: "姓名",
      dataIndex: "username",
      render: (text) => <a> {text} </a>,
    },
    {
      title: "性别",
      dataIndex: "sex",
      render: (text) =>
        text === 1 ? <Tag color="blue">男</Tag> : <Tag color="red">女</Tag>,
    },
    {
      title: "手机号",
      dataIndex: "tel",
    },
    {
      title: "角色",
      dataIndex: "role",
      render: (text) =>
        text === "管理员" ? (
          <Tag color="volcano"> {text} </Tag>
        ) : (
          <Tag color="green"> 普通会员 </Tag>
        ),
    },
    {
      title: "班级",
      dataIndex: "class_grade",
    },
    {
      title: "加入时间",
      dataIndex: "add_time",
      render(text) {
        const date = new Date(text);
        return date.toLocaleDateString();
      },
    },
    {
      title: "加入社团",
      dataIndex: "organization",
    },
    {
      title: "操作",
      render: (text, record) => (
        <Space size="middle">
          <a onClick={getinfo(record)}> 修改 </a>{" "}
          <a onClick={deletelist(record._id)}> 删除 </a>
        </Space>
      ),
    },
  ];
  // 分页
  const pagination = {
    total,
    pageSize: 5,
    onChange(page, pageSize) {
      setpage(page);
      console.log("current,size", page, pageSize);
    },
  };
  return (
    <>
      {type == "add" ? (
        <Froms
          visible={visible}
          onCreate={onCreate}
          onCancel={onCancel}
          title="添加会员"
          okText="添加"
        />
      ) : (
        <Froms
          visible={visible}
          data={info}
          onCreate={onChangeinfo}
          onCancel={onCancel}
          title="修改信息"
          okText="修改"
        />
      )}
      <div className="inputgroup">
        <Form layout="inline" onFinish={onFinish}>
          <Form.Item name="username" label="请输入姓名">
            <Input />
          </Form.Item>
          <Form.Item name="class_grade" label="请输入班级">
            <Input />
          </Form.Item>
          <Form.Item name="role" label="请选择角色">
            <Select
              style={{
                width: 120,
              }}
            >
              <Option value="管理员">管理员 </Option>
              <Option value="用户"> 普通会员 </Option>
            </Select>
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
          </Form.Item>
        </Form>
      </div>
      <div className="studentlists">
        <div className="add">
          <Button
            type="primary"
            onClick={() => {
              setVisible(true);
              settype("add");
            }}
          >
            添加
          </Button>
        </div>
        <div className="lists">
          <Table
            rowKey="_id"
            size="middle"
            columns={columns}
            dataSource={list}
            pagination={pagination}
          />
        </div>
      </div>
    </>
  );
}

export default Student;
